package labox.innovation.db;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.Map.Entry;

import labox.innovation.config.Config;
import labox.innovation.db.core.HeapByteBuffer;
import labox.innovation.db.core.SqlData;
import labox.innovation.db.manager.DBConnetionStateManager;
import labox.innovation.db.proxy.ConnectionProxy;
import labox.innovation.db.proxy.PreparedStatementProxy;
import labox.innovation.db.util.DbUtil;
import labox.innovation.db.util.SqlDataIdFactory;
import labox.innovation.gameserver.model.ConsignmentItem;
import labox.innovation.gameserver.model.ConsignmentManager;
import labox.innovation.gameserver.model.L2ItemInstance;
import labox.innovation.gameserver.model.itemcontainer.ConsignmentWarehouse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * ����ϵͳ
 * 
 * @author jacky
 * 
 */
public class ConsignmentDb {
	public static final Logger _log = LoggerFactory.getLogger(ConsignmentDb.class);
	private static final String SAVE_CONSIGNMENT="REPLACE INTO consignmentitem (charId,details,sliver,note,yaunbao) VALUES (?,?,?,?,?)";
	private static final String LOAD_CONSIGNMENT="select charId,details,sliver,note,yaunbao from consignmentitem";
	/**
	 * ɾ���ɫ�ļ������
	 */
	public static final String PHYSICAL_DELETE_CONSIGNMENT_BY_ID="delete from consignmentitem where charId=?";
	/**
	 * �������ϵͳ���浽��ݿ�
	 * 
	 * @param _allConsignmentHouse
	 * @throws SQLException 
	 */
	public static void storeConsignment(Map<Long, ConsignmentWarehouse> _allConsignmentHouse)  {
		Object[] params;
		ConnectionProxy con = null;
		PreparedStatementProxy state = null;
		try {
			if (DBConnetionStateManager.getDbState()) {
				con = ConnectionProxy.newInstance();
				if (con != null)
					state = con.prepareStatement(SAVE_CONSIGNMENT);
				for (Entry<Long, ConsignmentWarehouse> entry : _allConsignmentHouse.entrySet()) {
					HeapByteBuffer _buf = HeapByteBuffer.newInstance();
					_buf.clear();
					ConsignmentWarehouse _consignmentWarehouse = entry.getValue();
					_buf.writeByte(_consignmentWarehouse.getItemList().size());
					for (ConsignmentItem item : _consignmentWarehouse.getItemList()) {
						_buf.writeLong(item.getItemId());// ������Ʒ��Id
						_buf.writeInt(item.getItem().getItemId());// ��Ʒģ��ID
						_buf.writeInt(item.getPrice());// ��Ʒ�۸�
						_buf.writeInt(item.getPriceType());// ��Ʒ����
						_buf.writeLong(item.getShelveTime());// �ϼ�ʱ��
						_buf.writeLong(item.getConsignmentLength());// �ϼ�ʱ��
						_buf.writeByte(item.isShelve() ? 1 : 0);// �Ƿ��ϼ�
						// ��д���
						ItemsDb.commonWriteItem(item.getItem(), _buf);
					}
					_buf.flip();
					//
					SqlData data = null;

					if (!DbUtil.isDbNormal(DBConnetionStateManager.getDbState(), con, state)) {
						params = new Object[] { _consignmentWarehouse.getOwnerId(), _buf, _consignmentWarehouse.getMoneySliver(), _consignmentWarehouse.getMoneyNote(), _consignmentWarehouse.getMoneyYuanBao() };
						data = new SqlData(SqlDataIdFactory.createSqlId("consignmentitem", _consignmentWarehouse.getOwnerId()), SAVE_CONSIGNMENT, params);
						DBConnetionStateManager.addDbTask(data);

					} else {
						state.setLong(1, _consignmentWarehouse.getOwnerId());
						state.setBinaryStream(2, _buf, _buf.limit());
						state.setInt(3, _consignmentWarehouse.getMoneySliver());
						state.setInt(4, _consignmentWarehouse.getMoneyNote());
						state.setInt(5, _consignmentWarehouse.getMoneyYuanBao());
						int rs = state.executeUpdate();
						if(_log.isDebugEnabled()){
							_log.debug("������۲ֿ�  owner="+_consignmentWarehouse.getOwnerId()+" size="+_consignmentWarehouse.getItemList().size()+" result="+rs);
						}
						if (rs != PreparedStatementProxy.NETWORKDISCONNECTION) {
							HeapByteBuffer.recycle(_buf);
						} else {
							params = new Object[] { _consignmentWarehouse.getOwnerId(), _buf, _consignmentWarehouse.getMoneySliver(), _consignmentWarehouse.getMoneyNote(), _consignmentWarehouse.getMoneyYuanBao() };
							data = new SqlData(SqlDataIdFactory.createSqlId("consignmentitem", _consignmentWarehouse.getOwnerId()), SAVE_CONSIGNMENT, params);
							DBConnetionStateManager.addDbTask(data);

						}
					}
				}

			} else {
				// ��ݿⲻ��ʹ��ʱ

				for (Entry<Long, ConsignmentWarehouse> entry : _allConsignmentHouse.entrySet()) {
					HeapByteBuffer _buf = HeapByteBuffer.newInstance();
					_buf.clear();
					ConsignmentWarehouse _consignmentWarehouse = entry.getValue();
					_buf.writeByte(_consignmentWarehouse.getItemList().size());
					for (ConsignmentItem item : _consignmentWarehouse.getItemList()) {
						_buf.writeLong(item.getItemId());// ������Ʒ��Id
						_buf.writeInt(item.getItem().getItemId());// ��Ʒģ��ID
						_buf.writeInt(item.getPrice());// ��Ʒ�۸�
						_buf.writeInt(item.getPriceType());// ��Ʒ����
						_buf.writeLong(item.getShelveTime());// �ϼ�ʱ��
						_buf.writeLong(item.getConsignmentLength());// �ϼ�ʱ��
						_buf.writeByte(item.isShelve() ? 1 : 0);// �Ƿ��ϼ�
						// ��д���
						ItemsDb.commonWriteItem(item.getItem(), _buf);
					}
					_buf.flip();
					//
					SqlData data = null;
					params = new Object[] { _consignmentWarehouse.getOwnerId(), _buf, _consignmentWarehouse.getMoneySliver(), _consignmentWarehouse.getMoneyNote(), _consignmentWarehouse.getMoneyYuanBao() };
					data = new SqlData(SqlDataIdFactory.createSqlId("consignmentitem", _consignmentWarehouse.getOwnerId()), SAVE_CONSIGNMENT, params);
					DBConnetionStateManager.addDbTask(data);
				}

			}
		} catch (SQLException e) {
			_log.error("save consignment items error", Config.SERVER_ID, e);
			e.printStackTrace();
		} finally {
			if (state != null)
				state.close();
			if (con != null) {
				con.close();
			}
		}

	}

	/**
	 * ���ؼ���ϵͳ���
	 * @param _allConsignmentHouse
	 * @return
	 */
	public static Map<Long, ConsignmentWarehouse> restoreConsignment(Map<Long, ConsignmentWarehouse> _allConsignmentHouse) {
		ConnectionProxy con = null;
		PreparedStatementProxy state = null;
		HeapByteBuffer _buf = HeapByteBuffer.newInstance();
		ResultSet rest = null;
		try {
			if(!DBConnetionStateManager.getDbState())
				return null;
			con = ConnectionProxy.newInstance();
			if (con != null)
				state = con.prepareStatement(LOAD_CONSIGNMENT);
			if (DbUtil.isDbNormal(DBConnetionStateManager.getDbState(), con, state)) {
				rest = state.executeQuery();
				if (rest == null)
					return null;
				int _sliver;
				int _note;
				int _yaunbao;
				long _charId;
				byte[] _bytes;
				while (rest.next()) {
					_charId = rest.getLong("charId");
					/**
					 * �Զ�������� _allConsignmentHouse.put(_charId,
					 * consignmentWarehouse);
					 */
					_buf.clear();
					ConsignmentWarehouse consignmentWarehouse = new ConsignmentWarehouse(_charId);
					_sliver = rest.getInt("sliver");
					consignmentWarehouse.addMoney(20000, _sliver);
					_note = rest.getInt("note");
					consignmentWarehouse.addMoney(20001, _note);
					_yaunbao = rest.getInt("yaunbao");
					consignmentWarehouse.addMoney(20002, _yaunbao);
					_bytes = rest.getBytes("details");
					_buf.write(_bytes, 0, _bytes.length);
					_buf.flip();
					int _size = _buf.readByte();
					for (int i = 0; i < _size; i++) {
						long _object_id = _buf.readLong();// ������Ʒ��Id
						int _item_id = _buf.readInt();// ��ƷID
						int _price = _buf.readInt();// ��Ʒ�۸�
						int _priceType = _buf.readInt();// ��Ʒ����
						long shelveTime = _buf.readLong();// �ϼ�ʱ��
						long consignmentLength = _buf.readLong();// �ϼ�ʱ��
						boolean isShelve = _buf.readByte() != 0;// �Ƿ��ϼ�
						L2ItemInstance inst = ItemsDb.commonReadItem(_buf, _charId);// ��д������Ʒģ��
						ConsignmentItem consignmentItem = new ConsignmentItem(inst, consignmentLength, _price, _priceType, isShelve, null);
						consignmentItem.setShelveTime(shelveTime);//�����ϼ�ʱ��
						ConsignmentManager.initConsignmentItem(consignmentWarehouse, consignmentItem);
					}

				}
			}
		} catch (SQLException e) {
			_log.error("Error ConsignmentDb restoreConsignment", Config.SERVER_ID, e);
		} finally {
			HeapByteBuffer.recycle(_buf);
			if (rest != null)
				try {
					rest.close();
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
			if (state != null) {
				state.close();
			}
			if (con != null) {
				con.close();
			}

		}
		return _allConsignmentHouse;
	}
}
